#include "carmainwindow.h"
#include "ui_carmainwindow.h"
#include "paymainwindow.h"
#include "parkingmanager.h"
#include "timemanager.h"
#include "databasemanager.h"

#include <QDateTime>
#include <QDebug>
#include <QPixmap>
#include <QMessageBox>
#include <QHostAddress>
#include <QFile>
#include <QDir>
#include <QWidget>
#include <QString>

CarMainWindow::CarMainWindow(QWidget *parent)
    :QMainWindow(parent),
    ui(new Ui::CarMainWindow),
    m_recognizer(new LicensePlateRecognizer(this)),
    parkingManager(new ParkingManager(this)) // 直接初始化指针
{
    ui->setupUi(this);

    // 设置百度OCR的API Key和Secret Key（需要替换为你的）
    m_recognizer->setCredentials("gju2dY3C2ttizK01aF74Rz9z", "sjQ1DeT0aNTPkoJkjPRg6W9Z9ea2UCw2");

    // 初始化界面图片
    QPixmap pic(":/new/prefix1/icon/5.bmp");
    pic = pic.scaled(ui->label_pic->size());//根据显示控件的大小动态 调整 图片的大小
    ui->label_pic->setPixmap(pic);

    // 连接 TimeManager 的时间更新信号
    connect(TimeManager::instance(), &TimeManager::timeUpdatedHMS,
            this, [this](const QString &timeStr) {
                ui->label_time->setText(timeStr);  // 仅显示时分秒
            });
    QDateTime datetime = QDateTime::currentDateTime();
    qDebug()<<datetime.toString();

    // 表格控件初始化
    // 1.当前车辆表格控件
    QStringList header;
    header<<"车牌号"<<"进场时间";
    ui->tableWidget->setColumnCount(2);

    // 设置表格整体字体（影响表头和内容）
    for(int i=0; i<ui->tableWidget->columnCount(); i++)
    {
        QTableWidgetItem *item;
        //字段carid
        item = new QTableWidgetItem(header.at(i));

        //设置表头的样式
        QFont font = item->font();
        font.setBold(true);
        font.setPixelSize(20);
        item->setFont(font);
        //自适应列宽
        ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
        // 设置固定行高
        ui->tableWidget->verticalHeader()->setDefaultSectionSize(30);
        //插到表格控件中
        ui->tableWidget->setHorizontalHeaderItem(i,item);
    }

    // 2.历史车辆表格控件
    header<<"出场时间"<<"时长"<<"费用";
    ui->tableWidget_record->setColumnCount(5);

    for(int i=0; i<ui->tableWidget_record->columnCount(); i++)
    {
        QTableWidgetItem *item;
        //字段carid
        item = new QTableWidgetItem(header.at(i));

        //设置表头的样式
        QFont font = item->font();
        font.setBold(true);
        font.setPixelSize(20);
        item->setFont(font);
        //自适应列宽
        ui->tableWidget_record->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
        // 设置固定行高
        ui->tableWidget_record->verticalHeader()->setDefaultSectionSize(30);
        //插到表格控件中
        ui->tableWidget_record->setHorizontalHeaderItem(i,item);
    }

    // 3.vip车辆表格控件
    ui->tableWidget_vip->setColumnCount(5);

    for(int i=0; i<ui->tableWidget_vip->columnCount(); i++)
    {
        QTableWidgetItem *item;
        //字段carid
        item = new QTableWidgetItem(header.at(i));

        //设置表头的样式
        QFont font = item->font();
        font.setBold(true);
        font.setPixelSize(20);
        item->setFont(font);
        //自适应列宽
        ui->tableWidget_vip->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
        // 设置固定行高
        ui->tableWidget_vip->verticalHeader()->setDefaultSectionSize(30);
        //插到表格控件中
        ui->tableWidget_vip->setHorizontalHeaderItem(i,item);
    }

    //1、实例化一个TCP客户端类的对象
    m_tcpSocket = new QTcpSocket;
    //填入服务器的IP地址和端口号
    QString iP = QString("192.168.5.100");
    short port = 1234;
    //2、连接服务器
    m_tcpSocket->connectToHost(QHostAddress(iP),port);// 连接服务端IP和端口
    qDebug()<<"TCP 连接成功！";
    //当连接成功的时候，会自动触发connected().,关联槽函数，确认连接成功
    connect(m_tcpSocket,&QTcpSocket::connected,this,&CarMainWindow::onConnected);



    // 连接排序信号
    connect(ui->tableWidget_vip->horizontalHeader(), &QHeaderView::sectionClicked,
            this, &CarMainWindow::onVipHeaderClicked);
    connect(ui->tableWidget->horizontalHeader(), &QHeaderView::sectionClicked,
            this, &CarMainWindow::onCurrentHeaderClicked);
    connect(ui->tableWidget_record->horizontalHeader(), &QHeaderView::sectionClicked,
            this, &CarMainWindow::onRecordHeaderClicked);

    // 加载三个表格的初始数据
    loadTableData(ui->tableWidget, "curInfo", 1, Qt::DescendingOrder);
    loadTableData(ui->tableWidget_vip, "vipInfo", 1, Qt::DescendingOrder);
    loadTableData(ui->tableWidget_record, "recordInfo", 1, Qt::DescendingOrder);
}

CarMainWindow::~CarMainWindow()
{
    // 先释放所有数据库相关资源
    if(parkingManager) {
        delete parkingManager;
    }

    // 然后才删除UI
    delete ui;

    // 最后移除数据库连接
    QSqlDatabase::removeDatabase("car_parking_connection");
}

// 接收数据槽函数
void CarMainWindow::onConnected()
{
    qDebug()<<"-----------";
    //当连接成功了，如果服务器发送数据过来，会自动触发 readyRead信号，关联槽函数接收数据
    connect(m_tcpSocket,&QTcpSocket::readyRead,this,&CarMainWindow::onRecvDataSlot);
}

// 发送拍照命令按钮点击事件
void CarMainWindow::on_btn_start_2_clicked()
{
    m_waitingForImage = true; // 开始等待图片
    // 发送命令给摄像头进行抓拍
    //1、先获取你要发送的数据
    QString data = "1";
    //2、调用接口 发送数据
    m_tcpSocket->write(data.toLocal8Bit().data());
    ui->lineEdit->clear();
    //QTimer::singleShot(10000,this,&CarMainWindow::on_btn_start_clicked);//延时
}

// 接收服务器卡号跟图片并显示
void CarMainWindow::onRecvDataSlot()
{
    QByteArray newData = m_tcpSocket->readAll();

    // 检查是否是卡号数据
    if(newData.startsWith("CARD:"))
    {
        // 完全清空缓冲区
        imgeData.clear();

        // 提取卡号部分
        m_receivedCardNumber = QString(newData).remove(0, 5).trimmed();
        qDebug() << "Received card number:" << m_receivedCardNumber;

        // 立即处理卡号进出场
        QTimer::singleShot(0, this, &CarMainWindow::processCardCheckout);
        return;
    }

    // 处理图片数据
    imgeData.append(newData);

    // 检查是否接收完完整图片
    if(imgeData.size() >= 921654) // 使用>=而不是==
    {
        // 处理图片
        QPixmap pix;
        if(pix.loadFromData(imgeData))
        {
            pix = pix.scaled(ui->label_pic->size());
            ui->label_pic->setPixmap(pix);

            // 保存图片
            QFile file("2.bmp");
            if(file.open(QIODevice::WriteOnly))
            {
                file.write(imgeData);
                file.close();
            }

            imgeData.clear();
            m_waitingForImage = false;
            emit imageReceived();
        }
        else
        {
            qDebug() << "Failed to load image from received data";
            imgeData.clear();
        }
    }
}

// 识别车牌号
QString CarMainWindow::identifyCarid()
{
    // 加载图片
    m_currentImage = m_recognizer->loadImage("2.bmp");
    if (m_currentImage.isNull())
    {
        QMessageBox::warning(this, tr("错误"), tr("无法加载图片"));
        return "";
    }

    // 调用识别函数
    m_recognizer->recognizeLicensePlate(m_currentImage);

    QEventLoop loop;
    connect(m_recognizer, &LicensePlateRecognizer::recognitionCompleted,
            &loop, &QEventLoop::quit);
    connect(m_recognizer, &LicensePlateRecognizer::recognitionError,
            &loop, &QEventLoop::quit);
    loop.exec();  // 等待识别完成

    qDebug()<<"车牌号："<<m_recognizer->carNumber();
    return m_recognizer->carNumber();
}

// 车辆进场按钮点击事件
void CarMainWindow::on_btn_start_clicked()
{
    qDebug() << "车辆进场...";
    // 1. 检查数据库管理器是否初始化
    if(!DatabaseManager::instance()) {
        qDebug() << "DatabaseManager未初始化!";
        return;
    }

    // 2. 检查数据库是否打开
    if(!DatabaseManager::instance()->initialize()) {
        qDebug() << "数据库未打开!";
        return;
    }

    // 检查车位是否已满
    if (isParkingFull())
    {
        QMessageBox::warning(this, "车位已满",
                           "当前停车场车位已满，无法入场！");
        return;
    }
    qDebug() << "开始拍照...";
    // 1、触发拍照
    on_btn_start_2_clicked();
    qDebug() << "等待图片接收...";
    // 2、等待图片接收完成（超时机制避免死等）
    if (waitForImageReceival())
    {
        QMessageBox::warning(this, "超时", "未收到完整图片数据");
        return;
    }
    qDebug() << "图片接收完成，开始识别车牌...";
    // 3、进行车牌识别
    QString carId = identifyCarid();
    if(carId.isEmpty())
    {
        ui->lineEdit->setText("failed");
        return ;
    }

    // 4、检查该车辆是否已经在当前停车表中
    QString checkSql = QString("SELECT * FROM curInfo WHERE carid = '%1';").arg(carId);
    QSqlQuery checkQuery;
    if(checkQuery.exec(checkSql) && checkQuery.next())
    {
        QMessageBox::warning(this, tr("警告"), tr("该车辆已在停车场内，不能重复入场！"));
        return;
    }

    // 5、显示车牌和图片
    QPixmap pimax = QPixmap("2.bmp");
    pimax = pimax.scaled(ui->label_pic->size());
    ui->lineEdit->setText(carId);
    ui->label_pic->setPixmap(pimax);

    // 6、标签控件上 提示 该车辆入库（可选）
    QString time = QDateTime::currentDateTime().toString();
    QString text = QString("当前车辆:%1 进入停车场\n停车时间:%2").arg(carId).arg(time);
    //ui->label_3->setText(text);

    // 7、识别成功 入数据库操作
    if (!DatabaseManager::instance()->addCar(carId, time))
    {
        QMessageBox::warning(this, "错误", "添加车辆记录失败！");
        return;
    }

    // 8、在表格中显示，新增一行
    int row = ui->tableWidget->rowCount();
    ui->tableWidget->setRowCount(row+1);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);

    // 填充数据
    QTableWidgetItem *item;
    item = new QTableWidgetItem(carId);
    ui->tableWidget->setItem(row,0,item);
    item = new QTableWidgetItem(time);
    ui->tableWidget->setItem(row,1,item);

    // 在成功插入curInfo表后，通知ParkingManager更新
    if (parkingManager)
    {
        parkingManager->syncSlotsWithDatabase();
    }
}

// 普通结账按钮点击事件
void CarMainWindow::on_btn_stop_clicked()
{
    processCheckout(false); // 非VIP模式
}

// 会员结账按钮点击事件
void CarMainWindow::on_btn_stop_2_clicked()
{
    processCheckout(true); // VIP模式
}

// 结账函数
void CarMainWindow::processCheckout(bool isVip)
{
    // 1. 触发拍照
    on_btn_start_2_clicked();

    // 2. 等待图片接收完成（超时机制避免死等）
    if (waitForImageReceival())
    {
        QMessageBox::warning(this, "超时", "未收到完整图片数据");
        return;
    }

    // 3. 进行车牌识别
    QString carId = identifyCarid();
    if (carId.isEmpty())
    {
        ui->lineEdit->setText("failed");
        return;
    }
    ui->lineEdit->setText(carId);

    // 4. 遍历数据库的当前停车表信息，查找该车辆的入场时间
    QString sql = QString("SELECT * FROM curInfo WHERE carid = '%1';").arg(carId);
    QSqlQuery query;
    if (!query.exec(sql))
    {
        qDebug() << query.lastError().text();
        return;
    }

    QString enterTimeStr; // 入场时间
    while (query.next())  // 获取查询的结果
    {
        enterTimeStr = query.value("enterTime").toString();
    }

    // 5. 计算停车时长
    QDateTime lastTime = QDateTime::currentDateTime();
    QDateTime enterTime = QDateTime::fromString(enterTimeStr);
    int secs = enterTime.secsTo(lastTime);
    QString durationStr = formatDuration(secs);
    qDebug()<<"secs:"<<secs;//打印秒数

    // 6. 计算费用（VIP模式有折扣）
    double money = calculateFee(secs, isVip);

    // 7. 记录到数据库（VIP/普通表）
    if (!DatabaseManager::instance()->addParkingRecord(carId, enterTimeStr, lastTime.toString(), secs, money, isVip))
    {
        QMessageBox::warning(this, "错误", "添加停车记录失败！");
        return;
    }

    // 8. 更新UI表格（VIP/普通表）
    QTableWidget *targetTableWidget = isVip ? ui->tableWidget_vip : ui->tableWidget_record;
    int row = targetTableWidget->rowCount();
    targetTableWidget->setRowCount(row + 1);

    // 填充数据
    QTableWidgetItem *item;
    item = new QTableWidgetItem(carId);
    targetTableWidget->setItem(row, 0, item);
    item = new QTableWidgetItem(enterTimeStr);
    targetTableWidget->setItem(row, 1, item);
    item = new QTableWidgetItem(lastTime.toString());
    targetTableWidget->setItem(row, 2, item);
    item = new QTableWidgetItem(durationStr);
    targetTableWidget->setItem(row, 3, item);
    item = new QTableWidgetItem(QString::number(money, 'f', 2) + "元");
    targetTableWidget->setItem(row, 4, item);

    // 9. 从当前车辆表中删除
    if (!DatabaseManager::instance()->removeCar(carId))
    {
        QMessageBox::warning(this, "错误", "删除车辆记录失败！");
        return;
    }

    // 10. 从UI表格中删除对应的行
    for (int i = 0; i < ui->tableWidget->rowCount(); ++i)
    {
        if (ui->tableWidget->item(i, 0)->text() == carId)
        {
            ui->tableWidget->removeRow(i);
            break;
        }
    }

    // 11. 通知ParkingManager更新
    if (parkingManager)
    {
        parkingManager->syncSlotsWithDatabase();
    }

    // 12. 显示支付窗口（VIP/普通模式）
    auto mode = isVip ? PayMainWindow::VIP : PayMainWindow::Normal;
    PayMainWindow *widget = new PayMainWindow(this, mode);
    widget->setData(carId, enterTimeStr, lastTime.toString(), secs, money);
    widget->setAttribute(Qt::WA_DeleteOnClose);
    widget->show();// 非模态显示
}

// 卡号出站处理函数
void CarMainWindow::processCardCheckout()
{
    // 1. 检查是否收到卡号
    if (m_receivedCardNumber.isEmpty()) {
        QMessageBox::warning(this, "警告", "未接收到有效卡号！");
        return;
    }

    // 2. 触发拍照
    on_btn_start_2_clicked();

    // 3. 等待图片接收完成
    if (waitForImageReceival())
    {
        QMessageBox::warning(this, "超时", "未收到完整图片数据");
        return;
    }

    // 4. 进行车牌识别
    QString carId = identifyCarid();
    if (carId.isEmpty())
    {
        ui->lineEdit->setText("failed");
        return;
    }
    ui->lineEdit->setText(carId);

    // 5. 检查车辆是否在当前停车表中
    QString checkSql = QString("SELECT * FROM curInfo WHERE carid = '%1';").arg(carId);
    QSqlQuery checkQuery;
    bool isCarInParking = checkQuery.exec(checkSql) && checkQuery.next();

    if (!isCarInParking)
    {
        // 车辆不在场内，执行入站操作
        // 1. 检查车位是否已满
        if (isParkingFull())
        {
            QMessageBox::warning(this, "车位已满", "当前停车场车位已满，无法入场！");
            return;
        }

        qDebug()<<"卡号进场";

        // 2. 显示车牌和图片
        QPixmap pimax = QPixmap("2.bmp");
        pimax = pimax.scaled(ui->label_pic->size());
        ui->label_pic->setPixmap(pimax);

        // 3. 获取当前时间
        QString time = QDateTime::currentDateTime().toString();

        // 4. 识别成功 入数据库操作
        if (!DatabaseManager::instance()->addCar(carId, time)) {
            QMessageBox::warning(this, "错误", "添加车辆记录失败！");
            return;
        }

        // 5. 在表格中显示，新增一行
        int row = ui->tableWidget->rowCount();
        ui->tableWidget->setRowCount(row+1);
        ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);

        // 填充数据
        QTableWidgetItem *item;
        item = new QTableWidgetItem(carId);
        ui->tableWidget->setItem(row,0,item);
        item = new QTableWidgetItem(time);
        ui->tableWidget->setItem(row,1,item);

        // 6. 通知ParkingManager更新
        if (parkingManager)
        {
            parkingManager->syncSlotsWithDatabase();
        }

        QMessageBox::information(this, "入场成功", QString("车辆%1已成功入场").arg(carId));
    } else {
        // 车辆在场内，执行出站操作（原逻辑）
        QString enterTimeStr = checkQuery.value("enterTime").toString();

        qDebug()<<"卡号出场";

        // 6. 计算停车时长
        QDateTime lastTime = QDateTime::currentDateTime();
        QDateTime enterTime = QDateTime::fromString(enterTimeStr);
        int secs = enterTime.secsTo(lastTime);
        QString durationStr = formatDuration(secs);

        // 7. 因为是VIP免费出站，费用设为0
        double money = 0.0;

        // 8. 记录到VIP表
        if (!DatabaseManager::instance()->addParkingRecord(carId, enterTimeStr,
                                                         lastTime.toString(), secs, money, true)) {
            QMessageBox::warning(this, "错误", "添加VIP停车记录失败！");
            return;
        }

        // 9. 更新VIP表格
        int row = ui->tableWidget_vip->rowCount();
        ui->tableWidget_vip->setRowCount(row + 1);

        // 填充数据
        QTableWidgetItem *item;
        item = new QTableWidgetItem(carId);
        ui->tableWidget_vip->setItem(row, 0, item);
        item = new QTableWidgetItem(enterTimeStr);
        ui->tableWidget_vip->setItem(row, 1, item);
        item = new QTableWidgetItem(lastTime.toString());
        ui->tableWidget_vip->setItem(row, 2, item);
        item = new QTableWidgetItem(durationStr);
        ui->tableWidget_vip->setItem(row, 3, item);
        item = new QTableWidgetItem("免费");
        ui->tableWidget_vip->setItem(row, 4, item);

        // 10. 从当前车辆表中删除
        if (!DatabaseManager::instance()->removeCar(carId)) {
            QMessageBox::warning(this, "错误", "删除车辆记录失败！");
            return;
        }

        // 11. 从UI表格中删除对应的行
        for (int i = 0; i < ui->tableWidget->rowCount(); ++i) {
            if (ui->tableWidget->item(i, 0)->text() == carId) {
                ui->tableWidget->removeRow(i);
                break;
            }
        }

        // 12. 通知ParkingManager更新
        if (parkingManager) {
            parkingManager->syncSlotsWithDatabase();
        }

        // 13. 显示VIP支付窗口
        PayMainWindow *widget = new PayMainWindow(this, PayMainWindow::VIP);
        widget->setData(carId, enterTimeStr, lastTime.toString(), secs, money);
        widget->setAttribute(Qt::WA_DeleteOnClose);
        widget->show();
    }

}

// 将秒数转换为易读的时长字符串
QString CarMainWindow::formatDuration(int seconds)
{
    int hours = seconds / 3600;
    int minutes = (seconds % 3600) / 60;
    int secs = seconds % 60;

    // 统一格式：大于1小时显示"X小时Y分钟"，否则显示"X分钟"...否则显示"X秒钟"
    if (hours > 0)
    {
        return QString("%1小时%2分钟").arg(hours).arg(minutes);
    } else if (minutes > 0)
    {
        return QString("%1分钟").arg(minutes);
    } else
    {
        return QString("%1秒").arg(secs);
    }
}

// 计算停车费用
double CarMainWindow::calculateFee(int seconds, bool isVip)
{
    // 基础费率（元/小时）
    double baseRate = ui->spinBox->value();// 把spinBox的数值传给baseRate

    // 最小计费单位15分钟
    int minUnit = 15 * 60;
    // 计算计费单位数（向上取整）
    int units = (seconds + minUnit - 1) / minUnit;

    // 计算基础费用
    double fee = units * (baseRate / 4.0); // 15分钟费用=小时费率/4

    // 每日封顶费用100块钱
    double dailyCap = 100.0;
    if (fee > dailyCap)
    {
        fee = dailyCap;
    }

    // VIP折扣
    if (isVip)
    {
        fee *= 0.8; // 8折
    }

    return fee;
}

// 简化表头点击槽函数
void CarMainWindow::onVipHeaderClicked(int logicalIndex)
{
    Qt::SortOrder order = ui->tableWidget_vip->horizontalHeader()->sortIndicatorOrder();
    loadTableData(ui->tableWidget_vip, "vipInfo", logicalIndex, order);
}

void CarMainWindow::onCurrentHeaderClicked(int logicalIndex)
{
    Qt::SortOrder order = ui->tableWidget->horizontalHeader()->sortIndicatorOrder();
    loadTableData(ui->tableWidget, "curInfo", logicalIndex, order);
}

void CarMainWindow::onRecordHeaderClicked(int logicalIndex)
{
    Qt::SortOrder order = ui->tableWidget_record->horizontalHeader()->sortIndicatorOrder();
    loadTableData(ui->tableWidget_record, "recordInfo", logicalIndex, order);
}

// 通用的排序函数
void CarMainWindow::loadTableData(QTableWidget* table, const QString& tableName,
                                 int sortColumn, Qt::SortOrder sortOrder)
{
    table->setRowCount(0); // 清空表格

    // 定义列名映射
    QMap<int, QString> columnMap;
    if (tableName == "curInfo") {
        columnMap = {
            {0, "carid"},
            {1, "enterTime"}
        };
    } else if (tableName == "recordInfo" || tableName == "vipInfo") {
        columnMap = {
            {0, "carid"},
            {1, "enterTime"},
            {2, "lastTime"},
            {3, "sece"},
            {4, "money"}
        };
    }

    // 检查排序列是否有效
    if (!columnMap.contains(sortColumn)) {
        sortColumn = 1; // 默认按进场时间排序
    }

    // 获取数据
    QVector<QVariantMap> records;
    if (tableName == "curInfo") {
        records = DatabaseManager::instance()->getCurrentCars();
    } else if (tableName == "recordInfo") {
        records = DatabaseManager::instance()->getHistoryRecords(false);
    } else if (tableName == "vipInfo") {
        records = DatabaseManager::instance()->getHistoryRecords(true);
    }

    // 自定义排序
    std::sort(records.begin(), records.end(),
        [&columnMap, sortColumn, sortOrder](const QVariantMap &a, const QVariantMap &b)
    {
        QString fieldName = columnMap.value(sortColumn);
        QVariant valueA = a[fieldName];
        QVariant valueB = b[fieldName];

        // 特殊处理数值类型字段
        if (fieldName == "sece" || fieldName == "money")
        {
            if (sortOrder == Qt::AscendingOrder)
            {
                return valueA.toDouble() < valueB.toDouble();
            } else
            {
                return valueA.toDouble() > valueB.toDouble();
            }
        }
        // 处理时间字段
        else if (fieldName == "enterTime" || fieldName == "lastTime")
        {
            QDateTime timeA = QDateTime::fromString(valueA.toString());
            QDateTime timeB = QDateTime::fromString(valueB.toString());
            if (sortOrder == Qt::AscendingOrder)
            {
                return timeA < timeB;
            } else
            {
                return timeA > timeB;
            }
        }
        // 默认字符串比较
        else
        {
            if (sortOrder == Qt::AscendingOrder)
            {
                return valueA.toString().compare(valueB.toString(), Qt::CaseInsensitive) < 0;
            } else {
                return valueA.toString().compare(valueB.toString(), Qt::CaseInsensitive) > 0;
            }
        }
    });

    // 填充数据
    for (const auto& record : records) {
        int row = table->rowCount();
        table->insertRow(row);

        for (int col = 0; col < columnMap.size(); ++col) {
            QString fieldName = columnMap.value(col);
            QVariant value = record[fieldName];
            QTableWidgetItem* item = nullptr;

            if (fieldName == "sece") {
                int secs = value.toInt();
                item = new QTableWidgetItem(formatDuration(secs));
                item->setData(Qt::UserRole, secs);
            }
            else if (fieldName == "money") {
                double money = value.toDouble();
                item = new QTableWidgetItem(QString::number(money, 'f', 2) + "元");
                item->setData(Qt::UserRole, money);
            }
            else {
                item = new QTableWidgetItem(value.toString());
            }

            table->setItem(row, col, item);
        }
    }
}

// 检查车位状态
bool CarMainWindow::isParkingFull()
{
    // 获取当前车辆数量
    int currentCars = DatabaseManager::instance()->getCurrentCarCount();

    // 确保parkingManager已初始化
    if (!parkingManager) {
        qWarning() << "ParkingManager 未初始化，默认返回车位未满!";
        return false; // 或根据业务逻辑返回适当值
    }

    // 获取最大车位数
    int maxSlots = parkingManager->getMaxParkingSlots();
    return (currentCars >= maxSlots);
}

// 图片接收等待
bool CarMainWindow::waitForImageReceival()
{
    QEventLoop loop;
    QTimer timer;
    timer.setSingleShot(true);

    connect(this, &CarMainWindow::imageReceived, &loop, &QEventLoop::quit);
    connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
    timer.start(5000);//设置5秒超时
    loop.exec();// 阻塞等待，直到图片接收或超时

    return m_waitingForImage;
}


// 后台设置按钮点击事件
void CarMainWindow::on_aftersetbtn_clicked()
{
    qDebug() << "进入后台按钮被点击";

    // 如果窗口不存在则创建
    if (!parkingManager)
    {
        qDebug() << "窗口不存在，创建ParkingManager实例";
        parkingManager = new ParkingManager(this);
    }

    // 显示车位管理界面
    parkingManager->show();// 非模态

    // 可选: 将主界面最小化
    // this->showMinimized();

    // 可选: 模态显示(阻止主界面操作)
    // parkingManager->setWindowModality(Qt::ApplicationModal);
    // parkingManager->exec();
}
